<template>
  <div>
    <SectionTitle title="纳税人信息" class="mb-16"/>
    <el-form
      ref="taxpayerInfoForm"
      :rules="rules"
      :model="taxpayerInfo"
      :label-width="showMobilePage ? '90px' : '130px'"
      :label-position="showMobilePage ? 'left' : 'right'"
      class="lineHeight32">
      <el-row class="response-el-row" type="flex">
        <el-col :span="12" :class="{ 'indentation-form-item': showMobilePage }" class="responsive-col-lg-8">
          <el-form-item label="纳税人名称" prop="taxpayerId">
            <selectWithUserLoad
              ref="elSelect"
              v-model="taxpayerInfo.taxpayerId"
              :hide-select-list="defaultTaxpayer"
              :loadmore-method="getTaxpayerList"
              :add-new="hasRouteAuth('crm:customer:add')"
              :add-new-str="'添加新客户'"
              label-name="clientName"
              filterable
              collapse-tags
              clearable
              placeholder="请选择客户名称"
              @changeMethod="customerChange"
              @addNewClick="toCreateCustomer"/>
          </el-form-item>
        </el-col>
        <el-col :span="12" :class="{ 'indentation-form-item': showMobilePage }" class="responsive-col-lg-8">
          <el-form-item label="纳税人识别号" prop="taxpayerNum">
            <el-input
              v-model="taxpayerInfo.taxpayerNum"
              placeholder="自动从客户信息获取"
              name="taxpayerNum"
              maxlength="50"
              type="text"
              @input="valToTaxpayerNum($event, 'taxpayerNum')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开户行" prop="accountsBank">
            <el-input
              v-model="taxpayerInfo.accountsBank"
              placeholder="自动从客户信息获取"
              name="accountsBank"
              maxlength="50"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开票地址" prop="issueAddress">
            <el-input
              v-model="taxpayerInfo.issueAddress"
              placeholder="自动从客户信息获取"
              name="issueAddress"
              maxlength="50"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="开户账号" prop="accountNum">
            <el-input
              v-model="taxpayerInfo.accountNum"
              placeholder="自动从客户信息获取"
              name="accountNum"
              maxlength="50"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="注册电话" prop="phone">
            <el-input
              v-model="taxpayerInfo.phone"
              placeholder="自动从客户信息获取"
              name="phone"
              maxlength="50"
              type="text"
              @input="valToPureNum($event, 'phone')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :class="{ 'indentation-form-item': showMobilePage }" class="responsive-col-lg-8">
          <el-form-item label="一般纳税人证明" prop="certificateFile">
            <upAttachment
              ref="uploadImg"
              :hide-confirm="true"
              :file-list="taxpayerInfo.certificateFile"
              import-api="/common/file/upload"
              btn-text="上传文件"
              @complateSetData="completeSetData($event, 'certificateFile')"
              @removeFileList="removeFileList($event, 'certificateFile')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
import { getTaxpayerList, getTaxpayerInfo } from '@/api/issueInvoice';
import upAttachment from '@/components/Common/upAttachment/index';
import SectionTitle from '@/components/Title';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { cascaderSoft } from '@/utils/tools';
import { mapState } from 'vuex';
import { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';

export default {
  components: {
    upAttachment,
    selectWithUserLoad,
    SectionTitle
  },
  model: {
    prop: 'taxpayerInfo',
    event: 'changeValue'
  },
  props: {
    taxpayerInfo: {
      type: Object,
      default: () => ({})
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    financeData: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      getTaxpayerList,
      clientName: '',
      deptList: [],
      defaultProposer: [], // 默认申请人-当前用户
      customerList: {
        items: [],
        total: 0,
        page: 1,
        perPage: 20,
        isInit: true
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    rules() {
      // if (['电子发票（增值税专用发票）', '增值税专用发票', '纸质发票（增值税专用发票）'].includes(this.taxpayerInfo.invoiceType)) {
      if (this.taxpayerInfo.invoiceRequired) {
        return {
          taxpayerId: [{ required: true, message: '请选择客户名称', trigger: ['change', 'blur'] }],
          taxpayerNum: [{ required: true, message: '请输入纳税人识别号', trigger: ['change', 'blur'] }],
          accountsBank: [{ required: true, message: '请输入开户行', trigger: ['change', 'blur'] }],
          issueAddress: [{ required: true, message: '请输入开票地址', trigger: ['change', 'blur'] }],
          accountNum: [{ required: true, message: '请输入开户账号', trigger: ['change', 'blur'] }],
          phone: [{ required: true, message: '请输入注册电话', trigger: ['change', 'blur'] }]
        };
      }
      return {
        taxpayerId: [{ required: true, message: '请选择客户名称', trigger: ['change', 'blur'] }],
        taxpayerNum: [{ required: true, message: '请输入纳税人识别号', trigger: ['blur'] }]
      };
    },
    defaultTaxpayer() {
      const taxpayerInfo = this.taxpayerInfo;
      return taxpayerInfo.taxpayer && taxpayerInfo.taxpayerId
        ? [{ id: taxpayerInfo.taxpayerId, clientName: taxpayerInfo.taxpayer }] : [];
    }
  },
  watch: {
    'taxpayerInfo.invoiceType': {
      handler(val) {
        this.$nextTick(() => {
          this.$refs.taxpayerInfoForm.clearValidate();
        });
      }
    }
  },
  created() {
    this.getDeptList();
  },
  methods: {
    hasRouteAuth,
    // 提供给父组件来验证完整性
    validateForm(validate = true, index = 0) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs['taxpayerInfoForm'].validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(index);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    resetFormValidate() {
      this.$refs['taxpayerInfoForm'].resetFields();
    },
    // 获取部门
    getDeptList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptList = (res && res.data) || [];
        if (sort) cascaderSoft(this.taxpayerInfo.department, this.deptList);
      });
    },
    completeSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.taxpayerInfo[key]) {
        this.taxpayerInfo[key].push(fileList);
      } else {
        this.$set(this.taxpayerInfo, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.taxpayerInfo[key].splice(index, 1);
    },
    numInputChange(text, prop) {
      let str = text.replace(/[^\d.]/g, ''); // 只允许数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后3位
      this.taxpayerInfo[prop] = str;
    },
    // 纯数字
    valToPureNum(text, prop) {
      this.taxpayerInfo[prop] = text.replace(/[^\d-]/g, '');
    },
    valToTaxpayerNum(text, prop) {
      this.taxpayerInfo[prop] = text.replace(/[\u4e00-\u9fa5]/g, '');
    },
    // 用于手动触发表单验证
    triggerFormValidate() {
      this.$refs['taxpayerInfoForm'].validate();
    },
    // 纳税人名称改变的操作
    customerChange(data) {
      this.$set(this.taxpayerInfo, 'customType', data && data.type);
      this.$set(this.taxpayerInfo, 'taxpayer', data && data.clientName);
      // taxpayerType  0:公司  1:个人
      this.$set(this.taxpayerInfo, 'taxpayerType', data && data.clientType);
      if (!data) return;
      const financeTxnList = this.financeData;
      /**
        纳税人为个人时且是否到账(isArrival)为是：
        如果关联到账流水的付款人有和纳税人不一样则弹窗提示
       */
      if (this.taxpayerInfo.taxpayerType === 1 && this.taxpayerInfo.isArrival && financeTxnList && financeTxnList.length) {
        const isSame = financeTxnList.every(i => {
          return i.payName === this.taxpayerInfo.taxpayer;
        });
        if (!isSame) {
          showModal('请注意你填写的纳税人名称与付款人名称不一致，是否要继续填写?', '', {
            confirmButtonText: '继续填写',
            cancelButtonText: '暂不填写',
            type: 'warning',
            showClose: false,
            center: true,
            iconClass: 'charge-icon',
            customClass: 'del-message del-message-cancel'
          }, true).then(() => {
            this.fillContent(data);
            this.$refs.elSelect.inputBlur();
          }).catch(() => {
            this.$set(this.taxpayerInfo, 'customType', undefined);
            this.$set(this.taxpayerInfo, 'taxpayer', undefined);
            this.$set(this.taxpayerInfo, 'taxpayerType', undefined);
            this.$set(this.taxpayerInfo, 'taxpayerId', undefined);
            this.$emit('changeValue', this.taxpayerInfo);
            this.$refs.taxpayerInfoForm.clearValidate();
            this.$refs.elSelect.inputBlur();
          });
          return;
        }
      }
      this.fillContent(data);
    },
    // 从到账流水中填充纳税人信息
    receiptFillTax(company) {
      if (company.clientUniqueId) this.$set(this.taxpayerInfo, 'customType', company.clientUniqueId[0]);
      this.$set(this.taxpayerInfo, 'taxpayer', company.clientName);
      this.$set(this.taxpayerInfo, 'taxpayerType', company.clientType);
      this.$set(this.taxpayerInfo, 'taxpayerId', company.clientUniqueId);
      this.fillContent({ id: company.clientUniqueId });
    },
    fillContent(data) {
      getTaxpayerInfo(data.id).then(res => {
        const taxpayerKeys = ['taxpayerNum', 'accountsBank', 'issueAddress', 'accountNum', 'phone'];
        taxpayerKeys.forEach(key => {
          this.$set(this.taxpayerInfo, key, res.data[key]);
        });
        // this.$refs['taxpayerInfoForm'].validateField('certificateFile');
        this.$refs.taxpayerInfoForm.clearValidate();
      });
    },
    toCreateCustomer() {
      const routeUrl = this.$router.resolve({ name: 'createCustomer' });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.response-el-row {
  & ::v-deep {
    .el-input__inner {
      height: 32px;
      line-height: 32px;
      width: 240px;
    }
    .el-form-item__content {
      width: 240px;
    }
    .el-input__icon {
      line-height: 32px;
    }
    .el-form-item {
      margin-bottom: 24px;
    }
    .el-select {
      .el-input {
        .el-select__caret {
          color: #333333;
        }
      }
    }
    .indentation-form-item {
      .el-form-item {
        label {
          line-height: 1.2 !important;
        }
      }
    }
  }
  .custom-input {
    ::v-deep .el-input__inner {
      cursor: pointer;
    }
    &-icon {
      font-size: 14px;
      color: #666;
      margin-right: 5px;
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
</style>
